package top.zsyle.pet.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import top.zsyle.pet.domain.PetType;
import top.zsyle.pet.mapper.PetTypeMapper;
import top.zsyle.pet.service.IPetTypeService;
import top.zsyle.basic.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zsy
 * @since 2022-12-05
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;


    /**
     * 宠物类型的无限级树
     * @return
     */
    @Override
    public List<PetType> tree() {
        List<PetType> typeList = petTypeMapper.findAll();

        List<PetType> result = new ArrayList<>();

        Map<Long, PetType> map = typeList.stream().collect(Collectors.toMap(PetType::getId, type -> type));
        typeList.forEach(type->{
            if (null == type.getPid()){
                //顶级的宠物类型
                result.add(type);
            }else {
                PetType parent = map.get(type.getPid());
                if (null != parent){
                    parent.getChildren().add(type);
                }
            }
        });
        return result;
    }
}
